package com.zhucai.credit.bank.service.impl;

import java.math.BigDecimal;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhucai.credit.bank.bean.BankTransfer;
import com.zhucai.credit.bank.icbc.bean.GylinfoupSend;
import com.zhucai.credit.bank.icbc.service.IcbcService;
import com.zhucai.credit.bank.service.IFactoringService;
import com.zhucai.credit.bean.CreditRecord;
import com.zhucai.credit.common.CommonEnums.CrAprovalStatus;
import com.zhucai.credit.common.HelpConstant;
import com.zhucai.credit.model.CreditApplicationEntity;
import com.zhucai.credit.model.CreditInvoiceEntity;
import com.zhucai.credit.model.CreditRecordEntrity;
import com.zhucai.credit.monitor.service.INotificationService;
import com.zhucai.credit.repository.CreditApplicationRepository;
import com.zhucai.credit.repository.CreditInvoiceRepository;
import com.zhucai.credit.repository.CreditRecordRepository;
import com.zhucai.credit.service.impl.problem.ProblemSericeImpl;

@Service("ICBC_R_E_J")
public class IcbcFactoringServiceImpl implements IFactoringService {
	
	private static final Logger logger = LoggerFactory.getLogger(IcbcFactoringServiceImpl.class);
	
	@Autowired
	ProblemSericeImpl problemSericeImpl;
	@Autowired
	CreditRecordRepository creditRecordRepository;
	@Autowired
	CreditApplicationRepository creditApplicationRepository;
	@Autowired
	IcbcService icbcService;
	@Autowired
	CreditInvoiceRepository creditInvoiceRepository;
	@Resource(name = "EMAIL")
	private INotificationService emailINotificationService;
	
	@Override
	public CreditRecord preHandle(BankTransfer creditRecord) {

		return creditRecord;
	}

	@Override
	public CreditRecord apply(BankTransfer cr) {
		logger.info("### creditRecordToCCb 供应商审核通过的融资计划到工行审核 start");
		 String fail_reason="";
		 CreditRecord creditRecord = new CreditRecord();
		 
		 try {
				 CreditRecordEntrity cre = creditRecordRepository.findByTidAndStatusNot(cr.getTid(), HelpConstant.Status.delete);
				 if(cre==null){
					 /**
					  * 问题记录
					  */
					String problem = "### creditRecordToICBC方法失败  recordNo="+ cr.getRecordNo()+"查询融资记录为空";
					problemSericeImpl.setProblem(problem,"GYLINFOUP");
					
					fail_reason="确认融资失败:融资数据异常！！";
					
					logger.info("### creditRecordToICBC recordNo={}, 供应商审核通过的融资计划到工行审核  查询融资记录为空  ",cr.getRecordNo());
					creditRecord.setReturnMessage(fail_reason);
					emailINotificationService.notification(problem);
					return creditRecord;
				 }
				 //查询最近的有效的报名信息
				 CreditApplicationEntity cae = creditApplicationRepository.findCoopInfo(HelpConstant.Status.delete,cre.getParticipator(),cre.getOriginator(),CrAprovalStatus.BANK_SUCCESS.toString(),cre.getCrProdId());
				 //查询发票信息
				 CreditInvoiceEntity cie = creditInvoiceRepository.findOne(cre.getInvoiceTid());
				 
				 GylinfoupSend send = new GylinfoupSend();
				 //核心企业账号
				 send.setAccNo(cae.getEnterpriseAccount());
				 //账款金额（精确到分）
				 send.setDueAmt(cre.getCreditGetAmount().multiply(BigDecimal.valueOf(100)).longValue());
				 //总金额（多条时的）（精确到分）
				 send.setTotalAmt(cre.getCreditGetAmount().multiply(BigDecimal.valueOf(100)).longValue());
				 send.setTotalNum(1);
				 //操作类型（1、 新增2、 修改3、 删除   ）
				 send.setTranType(1);
				 SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
				 //发票日期
				 send.setDueDate(sf.format(cie.getInvoiceDate()));
				 //供应链编号
				 send.setGylCode(cae.getSupplyChainNumber());
				 //供应商组织机构代码
				 send.setMemberCode(cae.getAppOrgnNum());
				 //供应商企业名称
				 send.setMemberName(cae.getApplicantEnterpriseName());
				 //供应商监管账号
				 send.setMemberAccNo(cae.getSupEnterpriseAccount());
				 //账款到期日
				 send.setPlanDate(sf.format(cre.getLoanDate()));
				 //状态 0未确认1已确认
				 send.setStatus(1);
				 /**
				  * 凭证种类01 发票 99 其他
				  */
				 send.setVouchType("01");
				 //发票代码
				 send.setVouchCode(cie.getInvoiceCode());
				 //发票号
				 send.setVouchNo(cie.getInvoiceNo());
				 //融资单号
				 send.setContactNo(cre.getRecordNo());
				 
				 Map<String, String> rsMap = icbcService.updateGylinoup(send);
				 
				 String rsStatus=rsMap.get("RetCode");
				 String fSeqno = rsMap.get("fSeqno");
				 logger.info("### 工商银行提交融资记录数据 更新查询工行接口的序列号，fSeqno={}", fSeqno);
				
				 if(rsStatus!=null&&rsStatus.equals("0")){
					 creditRecord.setReturnStatus("OK");
					 //更新工行序列号
					 creditRecordRepository.updateFSeqno(cre.getTid(),fSeqno);
					 logger.info("### creditRecordToICBC recordNo={}, 供应商审核通过的融资计划到工行审核  成功  ",cr.getRecordNo());
				 }else{
					creditRecord.setReturnStatus("FAIL");
					fail_reason=rsMap.get("RetMsg");
					creditRecord.setReturnMessage(fail_reason);
					// 问题记录
					String problem = "recordNo="+ cre.getRecordNo()+"调用工行接口失败, GYLINFOUP errorMsg="+fail_reason;
					problemSericeImpl.setProblem(problem,"GYLINFOUP");
					
					emailINotificationService.notification(problem);
					logger.info("### creditRecordToICBC recordNo={}, 供应商审核通过的融资计划到工行审核  失败 ，err={},平台交易流水号  SerialNo={},指令包序列号  fSeqno={}",cr.getRecordNo(),rsMap.get("RetMsg"),rsMap.get("SerialNo"),rsMap.get("fSeqno"));
				 }
		} catch (SocketException e) {
			creditRecord.setReturnStatus("FAIL");
			fail_reason="连接超时,请稍后再试!";
			creditRecord.setReturnMessage(fail_reason);
			return creditRecord;
		}  catch (Exception e) {
			creditRecord.setReturnStatus("FAIL");
			fail_reason="网络异常!";
			fail_reason = e.getMessage();
			creditRecord.setReturnMessage(fail_reason);
			// 问题记录
			String problem = "### creditRecordToICBC 供应商审核通过的融资计划到工行审核 异常  recordNo="+ cr.getRecordNo()+"err="+e;
			problemSericeImpl.setProblem(problem,"GYLINFOUP");
			
			logger.info("### creditRecordToICBC recordNo={}, 供应商审核通过的融资计划到工行审核  失败,err={}",cr.getRecordNo(),e);
			
			emailINotificationService.notification("### 工行提交易信息异常recordNo="+cr.getRecordNo()+"err="+e);
			return creditRecord;
		}
		return creditRecord;
	}

	@Override
	public CreditRecord draw(BankTransfer creditRecord) {
		
		throw new UnsupportedOperationException("工行保理业务不支持平台支取操作");
	}

	@Override
	public CreditRecord pay(BankTransfer creditRecord) {
		
		throw new UnsupportedOperationException("工行保理业务不支持平台还款操作");
	}
}
